package pers.qianyu.month_202103.date_20210328;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 5714. 替换字符串中的括号内容
 * https://leetcode-cn.com/problems/evaluate-the-bracket-pairs-of-a-string/
 *
 * @author mizzle rain
 * @date 2021-03-28 14点05分
 */
public class Evaluate2 {
    public String evaluate(String s, List<List<String>> knowledge) {
        HashMap<String, String> map = new HashMap<>();
        for (List<String> strings : knowledge) {
            map.put(strings.get(0), strings.get(1));
        }
        int n = s.length();
        if (n == 0) return "";

        char[] arr = s.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (arr[i] != '(') {
                builder.append(arr[i]);
            } else {
                int k = i;
                while (k < n && arr[k] != ')') k++;
                String key = s.substring(i + 1, k);
                builder.append(map.getOrDefault(key, "?"));
                i = k;
            }
        }
        return builder.toString();
    }

    @Test
    public void test1() {
        String s = "(name)is(age)yearsold";
        List<List<String>> knowledge = Arrays.asList(
                Arrays.asList("name", "bob"),
                Arrays.asList("age", "two")
        );
        String r = new Evaluate2().evaluate(s, knowledge);
        Assert.assertEquals(r, "bobistwoyearsold");
    }

    @Test
    public void test2() {
        String s = "hi(name)";
        List<List<String>> knowledge = Arrays.asList(
                Arrays.asList("a", "b")
        );
        String r = new Evaluate2().evaluate(s, knowledge);
        Assert.assertEquals(r, "hi?");
    }

    @Test
    public void test3() {
        String s = "(a)(a)(a)aaa";
        List<List<String>> knowledge = Arrays.asList(
                Arrays.asList("a", "yes")
        );
        String r = new Evaluate2().evaluate(s, knowledge);
        Assert.assertEquals(r, "yesyesyesaaa");
    }

    @Test
    public void test4() {
        String s = "(a)(b)";
        List<List<String>> knowledge = Arrays.asList(
                Arrays.asList("a", "b"),
                Arrays.asList("b", "a")
        );
        String r = new Evaluate2().evaluate(s, knowledge);
        Assert.assertEquals(r, "ba");
    }
}
